package com.example.demo.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpsFileUtil {

    public static String post() throws Exception {
        File file = new File("/Users/wangfei/Downloads/20231213/key.ks"); // 公钥证书
        HttpPost httpPost = new HttpPost("https://172.17.27.124:30001/WEY.WebApp/auth/right/right/receivePost.html");
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(22000).build();
        httpPost.setConfig(requestConfig);
        List<NameValuePair> params = new ArrayList<NameValuePair>(); // params为可能要发送的请求参数
        params.add(new BasicNameValuePair("user.loginId", "Lin"));
        params.add(new BasicNameValuePair("user.employeeName","令狐冲"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Charset.forName("UTF-8"));
        httpPost.setEntity(entity);
        String content = null; // 接收内容
        try(
        CloseableHttpClient httpClient = createSSLHttpClient(true, file, "123456");
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);){
            HttpEntity responseEntity = httpResponse.getEntity();
            if (responseEntity != null) {
                content = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println(content);
            }
        }
        return content;
    }

    /**
     * Https请求，Context-Type为multipart/form-data
     * @param url 请求地址
     * @param params 请求参数，格式Map，有文件的，value值为File对象
     * @return 应答内容
     * @throws Exception 异常
     */
    public static String uploadFileMultipart(String url, Map<String, Object> params) throws Exception {
        String content = null; // http请求应答接收内容
        File file = new File("");
        HttpPost httpPost = new HttpPost("https://10.211.55.23:30001/WEY.WebApp/auth/right/right/receivePost.html"); // 参数url
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(22000).build();
        httpPost.setConfig(requestConfig);

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if(params != null) {
            for(Map.Entry<String, Object> param : params.entrySet()) {
                Object obj = param.getValue();
                if(obj instanceof String || obj instanceof  Double
                || obj instanceof  Integer || obj instanceof Long || obj instanceof Float) {
                    obj = String.valueOf(obj);
                    multipartEntityBuilder.addPart(param.getKey(), new StringBody(String.valueOf(obj), Charset.forName("UTF-8")));
                } else if (obj instanceof File) {
                    multipartEntityBuilder.addPart(param.getKey(), new FileBody((File)obj));
                } else if (obj instanceof List) {
                    List<Object> files = (List) obj;
                    for(Object object : files) {
                        if (object instanceof File) {
                            multipartEntityBuilder.addPart(param.getKey(), new FileBody((File)object));
                        } else {
                            throw new RuntimeException("文件参数：" + param.getKey() + "值不是File类型");
                        }
                    }
                } else {
                    throw new RuntimeException("文件参数：" + param.getKey() + "值不是File类型");
                }
            }
        }

        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);
        try(
                CloseableHttpClient httpClient = createSSLHttpClient(true, file, "123456");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);){
            HttpEntity responseEntity = httpResponse.getEntity();
            if (responseEntity != null) {
                content = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println(content);
            }
        }
        return null;
    }

    /**
     *
     * @param ignoreSsl 是否有证书
     * @param file 公钥证书
     * @return CloseableHttpClient实例
     * @throws Exception 描述
     */
    private static CloseableHttpClient createSSLHttpClient(boolean ignoreSsl, File file, String passwd) throws Exception {
        SSLContext sslContext = null;
        if (!ignoreSsl) {
            return HttpClients.createDefault();
        }

        if  (file.exists()) {
            sslContext = new SSLContextBuilder().loadTrustMaterial(file, passwd.toCharArray()).build();
        } else {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
        }
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(post());
    }
}